package com.oa.web.action;

import com.oa.utils.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


// 注意：oa2改造oa1：注解式开发解决xml中Servlet过多+模板方法设计模式(把类改造成方法)解决类爆炸
// 1. 注解式开发：
// name 相当于xml文件中<servlet-name>，可以省略
// urlPatterns 相当于xml配置文件中<url-pattern>,一个Servlet可以有多个路径
// @WebServlet(name = "DeptServlet", urlPatterns = {})
// 2.模板方法设计模式：
// 重写service方法(可以同时处理前端发来的doGet和doPost方法的情况)，而不是doGet或doPost方法
// 解决类爆炸核心：让一个请求对应一个方法，而不是对应一个类
// 模糊匹配：@WebServlet({"/dept/*"})也可，只要是路径以/dept开头，都走这个路径，但是获取路径不能用getServletPath
//          getServletPath只能获取到"/dept"
@WebServlet({"/dept/list","/dept/save","/dept/delete","/dept/detail","/dept/edit","/dept/modify"})
public class DeptServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String servletPath = request.getServletPath();

        if("/dept/list".equals(servletPath)){
            doList(request, response);
        }else if("/dept/save".equals(servletPath)){
            doSave(request, response);
        }else if("/dept/delete".equals(servletPath)){
            doDel(request, response);
        }else if("/dept/detail".equals(servletPath)){
            doDetail(request, response);
        }else if("/dept/edit".equals(servletPath)){
            doEdit(request, response);
        }else if("/dept/modify".equals(servletPath)){
            doModify(request, response);
        }

    }

    private void doList(HttpServletRequest request, HttpServletResponse response){
        //获取应用的根路径
        String contextPath = request.getContextPath();

        //设置响应内容及字符集。防止中文乱码
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter out = null;
        try {
            request.setCharacterEncoding("utf-8");
            out = response.getWriter();
        } catch (Exception  e) {
            e.printStackTrace();
        }


        out.print("<DOCTYPE html>");
        out.print("<tml lang='en'>");
        out.print("    <head>");
        out.print("        <meta charset='UTF-8'>");
        out.print("        <title>部门列表页面</title>");

        //<!--JavaScript代码-->
        out.print("<script type='text/javascript'>");
        out.print("    function del(dno){");
        out.print("        if(window.confirm('确认删除吗？')){");
        out.print("            document.location.href = '"+contextPath+"/dept/delete?deptno=' + dno");
        out.print("        }");
        out.print("     }");
        out.print("</script>");

        out.print("    </head>");
        out.print("    <body>");
        //<!--一级标题居中-->
        out.print("        <h1 align='center'>部门列表</h1>");
        //<!--hr 横线-->
        out.print("        <hr>");
        //<!--表格居中-->
        out.print("        <table border='1px' align='center' width='50%'>");
        out.print("            <tr>");
        //<!--th 字段-->
        out.print("                <th>序号</th>");
        out.print("                <th>部门编号</th>");
        out.print("                <th>部门名称</th>");
        out.print("                <th>操作</th>");
        out.print("            </tr>");
        //<!--以上内容是固定的-->"

        //连接数据库，查询所有的部门
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            //获取连接
            conn = DBUtil.getConnection();

            //获取数据库操作对象
            String sql = "select deptno,dname,loc from dept";
            ps = conn.prepareStatement(sql);

            //执行sql
            rs = ps.executeQuery();

            //处理结果集
            int i=0;
            while(rs.next()){
                String deptno = rs.getString("deptno");
                String dname = rs.getString("dname");

                //<!--以下是动态的-->
                out.print("            <tr>");
                //<!--数据-->"
                out.print("                <td>"+(++i)+"</td>");
                out.print("                <td>"+deptno+"</td>");
                out.print("                <td>"+dname+"</td>");
                out.print("                <td>");

                //删除分析
                //out.print("                    <a href=''>删除</a>");
                //<!--href 后设置为javascript:void(0)，表示点击超链接后只执行一段js代码，页面不进行跳转-->
                //<!--onclick 后面跟回调函数-->
                //<!--href页面跳转被禁止，所以用到del删除函数，然后再用超链接执行delete的Java代码-->
                //out.print("                    <a href='javascript:void(0)' onclick='window.confirm('亲，确认删除吗？')'>删除</a>");
                out.print("                    <a href='javascript:void(0)' onclick='del("+deptno+")'>删除</a>");

                out.print("                    <a href='"+contextPath+"/dept/edit?deptno="+deptno+"'>修改</a>");
                //<!--动态路径，从列表的servlet到详情的servlet-->
                out.print("                    <a href='"+contextPath+"/dept/detail?deptno="+deptno+"'>详情</a>");
                out.print("                </td>");
                out.print("            </tr>");
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            //释放资源
            DBUtil.close(conn,ps,rs);
        }
        //<!--以下内容是固定的-->
        out.print("        </table>");
        out.print("        <hr>");
        out.print("        <a href='"+contextPath+"/add.html'>新增部门</a>");
        out.print("    </body>");
        out.print("</html>");
    }
    private void doSave(HttpServletRequest request, HttpServletResponse response){
        // 设置字符集
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setCharacterEncoding("utf-8");

        String deptno = request.getParameter("deptno");
        String dname = request.getParameter("dname");
        String loc = request.getParameter("loc");

        Connection conn = null;
        PreparedStatement ps = null;
        //ResultSet rs = null;
        int row = 0;

        try {
            conn = DBUtil.getConnection();

            //下面这一行的deptno，dname,loc代表数据库中字段名
            String sql = "insert into dept value(?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1,deptno);
            ps.setString(2,dname);
            ps.setString(3,loc);

            row = ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBUtil.close(conn,ps,null);
        }

        if(row==1){
            //转发
            //request.getRequestDispatcher("/dept/list").forward(request,response);

            //重定向
            try {
                response.sendRedirect(request.getContextPath() + "/dept/list");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            //转发
            //request.getRequestDispatcher("/error.html").forward(request,response);

            //重定向
            try {
                response.sendRedirect(request.getContextPath() + "/error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private void doDel(HttpServletRequest request, HttpServletResponse response){
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //解决用转发跳转页面时乱码问题
        response.setCharacterEncoding("utf-8");

        try {
            PrintWriter out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String deptno = request.getParameter("deptno");

        Connection conn = null;
        PreparedStatement ps = null;
        //ResultSet rs = null;
        int row = 0;

        try {
            conn = DBUtil.getConnection();

            //开启事务
            conn.setAutoCommit(false);

            String sql = "delete from dept where deptno=?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,deptno);

            row = ps.executeUpdate();

            //事务提交
            conn.commit();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            //遇到异常回滚
            try {
                conn.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        } finally {
            DBUtil.close(conn,ps,null);
        }

        //判断是否删除成功
        if(row==1){
            //删除成功
            //仍然跳转到部门列表页面，需要指向DeptListServlet，可以用转发
            //转发：从一个Servlet跳转到另一个Servlet，但网页地址不会跳转，只是跳转了页面
            //request.getRequestDispatcher("/dept/list").forward(request,response);

            //重定向
            try {
                response.sendRedirect(request.getContextPath() + "/dept/list");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            //删除失败
            //跳转到删除失败页面
            //request.getRequestDispatcher("/error.html").forward(request,response);

            //重定向
            try {
                response.sendRedirect(request.getContextPath() + "/error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private void doDetail(HttpServletRequest request, HttpServletResponse response){
        String deptno = request.getParameter("deptno");

        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }

        out.print("<!DOCTYPE html>");
        out.print("<html lang='en'>");
        out.print("    <head>");
        out.print("        <meta charset='UTF-8'>");
        out.print("        <title>部门详情</title>");
        out.print("    </head>");
        out.print("    <body>");
        out.print("    <h1>部门详情</h1>");
        out.print("    <hr>");

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();

            String sql = "select dname,loc as location from dept where deptno = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,deptno);

            //这个结果集只有一条记录,deptno是主键，不能重复
            rs = ps.executeQuery();

            int i=0;
            if(rs.next()){
                String dname = rs.getString("dname");
                String location = rs.getString("location");

                out.print("        <tr>");
                out.print("            部门编号:<th>"+deptno+"</th><br>");
                out.print("            部门名称:<th>"+dname+"</th><br>");
                out.print("            部门位置:<th>"+location+"</th><br>");
                out.print("        </tr>");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DBUtil.close(conn,ps,rs);
        }

        out.print("    <hr>");
        out.print("        <input type='button' value='后退' onclick='window.history.back()'>");
        out.print("    </body>");
        out.print("</html>");
    }
    private void doEdit(HttpServletRequest request, HttpServletResponse response){
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=utf-8");
        String contextPath = request.getContextPath();

        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String deptno = request.getParameter("deptno");

        out.print("<!DOCTYPE html>");
        out.print("<html lang='en'>");
        out.print("    <head>");
        out.print("        <meta charset='UTF-8'>");
        out.print("        <title>修改部门</title>");
        out.print("    </head>");
        out.print("    <body>");
        out.print("        <h1>修改部门</h1>");
        out.print("        <hr>");
        out.print("        <form action='"+contextPath+"/dept/modify?deptno="+deptno+"' method='post'>");



        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();

            String sql = "select * from dept where deptno = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,deptno);

            rs = ps.executeQuery();

            if(rs.next()){
                String dname = rs.getString("dname");
                String loc = rs.getString("loc");

                out.print("                部门编号<input type='text' name='deptno' value='"+deptno+"' readonly> <br>");
                out.print("                部门名称<input type='text' name='dname' value='"+dname+"'><br>");
                out.print("                部门位置<input type='text' name='loc' value='"+loc+"'><br>");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBUtil.close(conn,ps,rs);
        }

        out.print("            <input type='submit' value='修改'><br>");
        out.print("        </form>");
        out.print("    </body>");
        out.print("</html>");
    }
    private void doModify(HttpServletRequest request, HttpServletResponse response){
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=utf-8");

        String deptno = request.getParameter("deptno");
        String dname = request.getParameter("dname");
        String loction = request.getParameter("loc");

        Connection conn = null;
        PreparedStatement ps = null;
        int row = 0;

        try {
            conn = DBUtil.getConnection();

            String sql = "update dept set dname = ?,loc = ? where deptno = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,dname);
            ps.setString(2,loction);
            ps.setString(3,deptno);

            row = ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBUtil.close(conn,ps,null);
        }

        if(row == 1){
            //转发
            //request.getRequestDispatcher("/dept/list").forward(request,response);

            //重定向
            try {
                response.sendRedirect(request.getContextPath() + "/dept/list");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            //转发
            //request.getRequestDispatcher("/error.html").forward(request,response);

            //重定向
            try {
                response.sendRedirect(request.getContextPath() + "/error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
